package com.example.bookstore.security;

import com.example.bookstore.accessctro.RolePermission;
import com.example.bookstore.utils.CheckRoleUtil;
import com.example.bookstore.vo.ResultVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(200)
public class RoleAspect {

    @Pointcut("@annotation(com.example.bookstore.accessctro.RolePermission)")
    private void permisson(){
    }

    /**
     * 给添加RolePermission注解的方法校验权限，而不必每个方法内都判断权限
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("permisson() && @annotation(rolePermission)")
    public Object advice(ProceedingJoinPoint joinPoint, RolePermission rolePermission) throws  Throwable {
        ResultVO r = null;
        r = (ResultVO) joinPoint.proceed();
        String[] key = rolePermission.key();
        if(key == null){
            r.setCode(600);
            r.setMessage("权限名称不能为空");
            r.setData(null);
            return r;
        }
        //校验当前登录用户是否有该权限
        CheckRoleUtil checkRoleUtil = new CheckRoleUtil();
        if(!checkRoleUtil.CheckRole(key)){
            r.setCode(600);
            r.setMessage("没有此操作权限！");
            r.setData(null);
        }
        return r;
    }
}
